package com.echo.im.common.util;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;

import java.util.Date;

public final class JwtUtil {

    private static final String secret="IKDiqVmn0VFU";

    private JwtUtil() {
    }


    public static String createTempToken(String business,String userId,Object info, long expireIn) {
        try {
            Date date = new Date(System.currentTimeMillis() + expireIn * 1000);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            return JWT.create()
                    .withClaim("business",business)
                    .withClaim("info", JSONObject.toJSONString(info))
                    .withClaim("userId",userId)
                    //过期时间
                    .withExpiresAt(date)
                    //token的密钥
                    .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    public static <T> T parseAndCheckTempToken(String business,String userId, String token, Class<T> clazz) {
        try {
            // 验证是否有效
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);

            if(!business.equals(JWT.decode(token).getClaim("business").asString())){
                return null;
            }

            // 验证临时token使用者
            if (!userId.equals(JWT.decode(token).getClaim("userId").asString())) {
                return null;
            }

            // 返回指定类型的信息类
            String infoJson = JWT.decode(token).getClaim("info").asString();
            return JSONObject.parseObject(infoJson, clazz);

        } catch (Exception e) {
            return null;
        }
    }

}
